<template>
  <div class="my-container animate__animated animate__bounceInLeft">
    <div class="Login" v-if="isShow">
      <div class="login-left">
        <div>
          <p class="small">Welcome to</p>
          <p class="big">合家团圆 聊天室</p>
        </div>
      </div>
      <div class="login-right">
        <div class="content">
          <div>
            <label for="username" class="iconfont icon-ziyuanxhdpi">
              用户名</label
            >
            <input type="text" class="user" id="username" v-model="inputUsername" />
          </div>
          <div class="chooseAvatar flex-1">
            <label for="avatar" class="iconfont icon-icon26"> 选择头像</label>
            <ul class="avatarWrap">
              <li v-for="(img, index) in imgUrl" :key="img">
                <img alt="none"
                  :src="getImageUrl(img)"
                  @click="clickImg(index, img)"
                  :class="{ active: currentIndex === index ? true : false }"
                />
              </li>
            </ul>
          </div>
          <div class="flex flex-1 items-center justify-center">
            <el-button type="primary" @click="loginRoom" :icon="Monitor" plain round>进入</el-button>
          </div>
        </div>
      </div>
    </div>
    <Room
      v-else
      :user="user"
      :userList="userList"
      ref="chatroom"
      @sendServer="sendServer"
      :message="message"
      @handleFile="handleFile"
    />
  </div>
  
</template>

<script lang="ts" setup>
  import { ref, onMounted } from "vue";
  import io from 'socket.io-client' //引入socket.io-client
  import { ElMessage } from 'element-plus'
  import { Monitor } from '@element-plus/icons-vue'
  import Room from '../components/Interact-Room.vue';
  import useStore from "../stores"

  const { interactState } = useStore()

  const chatroom = ref();  // 获取子组件暴露的方法
  const isShow = ref<boolean>(true); // 控制显示进入还是聊天室

  // ----------------------------------------------------------------
  const imgUrl = [ // 可选的用户图片
    'one.jpg', 'two.jpg', 'three.jpeg', 'four.jpg', 'five.jpg',
    'six.jpg', 'seven.jpg', 'eight.jpg', 'nine.jpg', 'ten.jpeg'
  ];
  const currentImg = ref<string>('one.jpg'); // 当前的用户图片
  const currentIndex = ref<number>(0);
  const clickImg = (index: number, img: string) => {
    currentIndex.value = index
    currentImg.value = img
  }
  const handleFile = (file: any) => { // 用于上传图片
    socket.emit('sendImage', { ...user.value, file })
  }

  const getImageUrl = (name: string) => {
    return new URL(`../assets/avatar/${name}`, import.meta.url).href
  }

  // ----------------------------------------------------------------
  type User = { avatar: string, msg: string, username: string }
  type UserList = Array<{ avatar: string, username: string }>
  type Message = { avatar: string, msg: string, username: string }

  const inputUsername = ref<string>(''); // 用户的名称输入
  const user = ref<User>({ // 用户的信息
    avatar: "", msg: "",username: ""
  }); 
  const userList = ref<UserList>([]); // 包含多个用户的列表
  const message: any = ref<Message>({  // 接收的消息对象
    avatar: "", msg: "",username: ""
  });

  let socket: any = null; // 初始化websocket

  const sendServer = (content: string) => {
    const { username, avatar } = user.value
    socket.emit('sendMessage', { msg: content, username, avatar })
  };

  const loginRoom = () => {   // 登陆进去聊天室
    const username = inputUsername.value;  // 1.获取用户名
    if (!username.trim()) {
      ElMessage({
        message: '请输入用户名哦',
        type: 'info',
        grouping: true,
      });
      return;
    }

    socket.emit('login', { // 2.需要告诉socket io服务，进行进入
      username,
      avatar: currentImg.value,
    });
  };
  onMounted(() => { // 聊天室的主要功能
    socket = io(process.env.VUE_APP_URL || "/"); // 1.连接服务器，baseURL:process.env.VUE_APP_URL || "/admin/api"
    socket.on('userExit', (data: any) => alert(data.msg)); // 2.监听进入失败的请求
    socket.on('loginsuccess', (data: any) => { // 3.监听进入成功的请求
      ElMessage({
        message: '即将进入',
        type: 'success',
        grouping: true,
        onClose: () => {
          user.value = data
          isShow.value = false
        },
        duration: 1500
      });
      
    });
    socket.on('addUser', (data: any) => {
      interactState.setJoinRoom(data)
    });
    socket.on('leaveroom', (data: any) => {
      interactState.setLeaveRoom(data)
      chatroom.value.haveOneleaveRoom();
    });
    socket.on('userList', (data: any) => { // 监听用户列表的信息
      userList.value = data
    });
    socket.on('receiveMessage', (data: any) => { // 监听聊天的消息
      message.value = data // 把接收到的消息显示到聊天窗口中
    });
    socket.on('receiveImage', (data: any) => { // 监听图片的消息
      chatroom.value.handleImage(data) // 把接收到的图片显示到聊天窗口中
    });
  });
</script>

<script lang="ts">
  export default {
    name: "interact"
  }
</script>

<style lang="less" scoped>
.my-container{
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.Login {
  width: 45%;
  min-width: 650px;
  height: 50%;
  min-height: 350px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #333;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 0 10px #fff;
  .login-left {
    width: 240px;
    height: 100%;
    background-color: rgba(64, 168, 255, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    .small {
      color: #f1e9e9;
      font-size: 14px;
      font-family: sans-serif;
    }
    .big {
      font-size: 20px;
      font-weight: 600;
      margin-top: 5px;
      color: #f1e9e9;
      font-family: sans-serif;
    }
  }
  .login-right {
    flex: 1;
    min-width: 450px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    .icon-ziyuanxhdpi,
    .icon-icon26 {
      color: #353c73;
    }
    label {
      color: #000;
      font-size: 14px;
    }
    .content {
      width: 90%;
      height: 80%;
      display: flex;
      flex-wrap: wrap;
      flex-direction: column;
      justify-content: space-between;
      .user {
        width: 95%;
        border: 1px solid #ccc;
        font-size: 14px;
        line-height: 30px;
        padding-left: 10px;
        display: block;
      }
      .chooseAvatar {
        margin-top: 4%;
        width: 100%;
        .avatarWrap {
          width: 95%;
          display: flex;
          flex-wrap: wrap;
          justify-content: center;
          align-items: center;
          border: 1px solid #ccc;
          li {
            cursor: pointer;
            width: 70px;
            height: 70px;
            display: flex;
            justify-content: center;
            align-items: center;
            img {
              width: 60px;
              height: 60px;
            }
            .active {
              border: 3px solid #2980b9;
            }
          }
        }
      }
    }
  }
}
</style>
